package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhengjd
 * @date 2020/5/12 16:13
 */
@Service
public class SearchResultMapperImpl implements SearchResultMapper {
    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
        //设置返回的rows集合
        List<T> content = new ArrayList<T>();
        //获取总记录数
        SearchHits hits = response.getHits();
        if (hits == null || hits.getTotalHits()<=0){
            return new AggregatedPageImpl<T>(content);
        }
        //设置高亮数据
        for (SearchHit hit : hits) {
            //获取没有高亮的数据
            String sourceAsString = hit.getSourceAsString();
            SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);
            //获取设置高亮的域和高亮数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields !=null && highlightFields.size()>0 && highlightFields.get("name") != null && highlightFields.get("name").getFragments() != null){
                HighlightField highlightField = highlightFields.get("name");
                Text[] fragments = highlightField.getFragments();
                StringBuffer sb = new StringBuffer();
                for (Text fragment : fragments) {
                    sb.append(fragment.string());
                }
            if (sb.toString().length()>0){
                //替换成高亮数据
                skuInfo.setName(sb.toString());
            }
            //content.add((T) skuInfo);

            }
            content.add((T) skuInfo);
        }

        //设置返回的查询个数
        long total = hits.getTotalHits();
        //设置返回的聚合结果集
        Aggregations aggregations = response.getAggregations();
        String scrollId = response.getScrollId();
        return new AggregatedPageImpl<T>(content,pageable,total,aggregations,scrollId);
    }
}
